﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.IO;

namespace MKIB3Game
{
 public   class Connector: IConnector
    {
        public static string ip = "127.0.0.1";
        public static int port = 666;

        TcpClient client;
        //private string ip = "85.214.103.114";
        //private int port = 110;
        Sender sender;
        Receiver receiver;
        IParser parser;
      
    
        public Connector()
        {
           
            init();
        }
        public void reconnect()
        {
            try
            {
                Console.WriteLine("Trying to reconnect after");
                for (int i = 10; i > 0; i--)
                {
                    Console.WriteLine("in " + i);
                    Thread.Sleep(1000);
                }
                this.init();
            }
            catch (IOException)
            {
                Console.WriteLine("recoonecting not successfull, trying again");
                this.reconnect();
            }
        }
        private void init()
        {
            Console.WriteLine("Init Connection \n ___connecting with Server IP:" + ip + ":" + port + "...");
             try
            {
                client = new TcpClient();  
                client.Connect(ip, port);
                            Console.WriteLine("___connected");
                            Console.WriteLine("___Initializing sender and receiver...");
                receiver =  new Receiver(client, this); 

                sender = new Sender(client); 
                            Console.WriteLine("___sender and receiver initialized");
                            Console.WriteLine("Init Connection done"); 
            }
            catch (SocketException e)
            {
                Console.WriteLine(e.Message + "\n");
                reconnect();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message + "\n");
            }
        }

        public Connector(IParser parser) : this(){
            this.parser = parser;
            Console.WriteLine("Connector mit Parser verknüpft");
        } 
        public Sender getSender(){
            return sender;
        }
        public Receiver getReceiver(){
            return receiver;
        }
        public virtual void close()
        {
            client.Close();
        }
       public void send(string message)
        {
            sender.send(message);
        }
       public string readBufferedLine()
       {           
           return receiver.readBufferLine();
       }
    }
}
